<template>
  <div class="newaddress">
    <van-nav-bar
      title="新增地址"
      left-arrow
      class="header"
      @click-left="onClickLeft"
    />

    <van-address-edit
      :area-list="areaList"
      show-set-default
      show-search-result
      :tel-validator="str => str.length > 3"
      :search-result="searchResult"
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      @save="onSave"
      @change-detail="onChangeDetail"
      :address-info="addressInfo"
/>
  </div>  
</template>

<script>
import { mapActions, mapState } from 'vuex';

export default {
  name: 'Newaddress',
  data() {
    return {
      areaList: {
        province_list: {
          110000: '北京市',
          120000: '天津市',
        },
        city_list: {
          110100: '北京市',
          120100: '天津市',
        },
        county_list: {
          110101: '东城区',
          110102: '西城区',
        },
      },
      searchResult: [],
      addressInfo: {}
    }
  },
  created() {
    const { id } = this.$route.query;
    // 如果id 存在则带遍需要会显示数据
    if(id) {
      this.addressInfo = this.addressList.filter(item => item.id == id)[0];
      this.addressInfo.addressDetail = this.addressInfo.address;
    }
  },
  computed: {
    ...mapState(['addressList'])
  },
  methods: {
    // 结构 vuex 中的 axtions 方法
    ...mapActions(['addAddressList']),
    // 按钮返回
    onClickLeft() {
      this.$router.push('/index/home/receiving');
    },
    onSave(content) {
      const { id } = this.$route.query;
      // 1. 点击把数据保存到 vuex 中
      this.addAddressList({ content, id });

      // 2. 跳转页面
      this.$router.push('/index/home/receiving');
    },
    onChangeDetail(val) {
      if (val) {
        this.searchResult = [
          {
            name: '黄龙万科中心',
            address: '杭州市西湖区',
          },
        ];
      } else {
        this.searchResult = [];
      }
    },
  }
}
</script>

<style lang='scss'>
.header {
  background-image: linear-gradient(90deg,#0af,#0085ff);
  color: #fff;
  .van-nav-bar__text, .van-nav-bar__arrow, .van-nav-bar__title {
    color: #fff;
  }
}
</style>
